import { lazyReportBatch } from "../report";
export const originalProto = XMLHttpRequest.prototype;
export const originalSend = originalProto.send;
export const originalOpen = originalProto.open;

interface XHRWithMeta extends XMLHttpRequest {
  url?: string;
  method?: string;
  startTime?: number;
  endTime?: number;
  duration?: number;
}
type bodyType= Document | XMLHttpRequestBodyInit | null | undefined;

function overwriteOpenAndSend(): void {
  // 重写 open 方法，记录 method 和 url
  originalProto.open = function newOpen(
    this: XHRWithMeta,
    method: string,
    url: string,
    ...args: any[]
  ): void {
    this.method = method;
    this.url = url;
    originalOpen.apply(this, [method, url, true]);
  };

  // 重写 send 方法，添加监听器，记录时间
  originalProto.send = function newSend(this: XHRWithMeta, body?: bodyType): void {
    this.startTime = Date.now();

    const onLoaded = (): void => {
      this.endTime = Date.now();
      this.duration = this.endTime - (this.startTime ?? this.endTime);

      const { url, method, startTime, endTime, duration, status } = this;

      const reportData = {
        type: 'performance',
        subType: 'xhr',
        url: url ?? '',
        method: (method ?? 'GET').toUpperCase(),
        status,
        startTime,
        endTime,
        duration,
        success: status >= 200 && status < 300,
      };
      console.log(reportData);

      // TODO: 上报数据
      //lazyReportBatch(reportData);

      this.removeEventListener('loadend', onLoaded, true);
    };

    this.addEventListener('loadend', onLoaded, true);
    originalSend.apply(this, [body]);
  };
}

export default function xhrMonitor(): void {
  overwriteOpenAndSend();
}

